import { invoke } from "@tauri-apps/api/core";

export interface LZIZY_Video_Base {
  id:number,
  name:string,
  cover_url:string
}

export interface LZIZY_Video {
  name: string,
  genres: string,
  cover_url: string,
  actor: string[],
  intro: string,
  director: string[],
  region: string,
  year: string,
  update_time: string,
  language: string,
  update_state: string,
  play_infos: EpisodeInfo[]
}
export interface EpisodeInfo {
	title:string,
	url:string
}

export interface CustomStruct {
  name: string,
  age: number,
  personal_property: string[],
	marriage: boolean
}

export interface ConcurrentRequestResult {
  body: string,
  duration: number
}

export async function customStruct() {
  try {
    return await invoke<CustomStruct>("get_custom_struct").then((v) => v);
  } catch (e) {
    // throw(e);
    // console.log(`[定义方]：后端get_custom_struct接口发生错误！`);
    return Promise.reject(e);
  }
}

export async function proxyFetch(url: string, options?: RequestInit) {
  const { method = "GET", headers, body } = options || {};
  try {
    const result = await invoke<string>("proxy_fetch", {url, method, headers: headers || null, body: body ? String(body) : null});
    console.log(`[proxyFetch]: ${result}`);
    
    return new Response(result);
  } catch (error) {
    return new Response(JSON.stringify({ error }), { status: 500 });
  }
}

export async function proxyConcurrentRequests(urls: string[], options?: RequestInit):Promise<ConcurrentRequestResult[]> {
 const { method = "GET", headers, body } = options || {};
  try {
    // const result = await invoke<string>("proxy_fetch", {url, method, headers: headers || null, body: body ? String(body) : null});
    const result = await invoke<ConcurrentRequestResult[]>("proxy_concurrent_requests", {urls, method, headers: headers || null, body: body ? String(body) : null});
    console.log(`[proxy_concurrent_requests]: ${result}`);
    return result;
  } catch (e) {
    // return new Response(JSON.stringify({ error }), { status: 500 });
    return Promise.reject(e);
  } 
}

export async function getOptimalRoute() {
  try {
    return await invoke<(string)>("get_optimal_route");
  } catch(e) {
    return Promise.reject(e);
  }
}

export async function getChannelVideo(channelIndex: number):Promise<LZIZY_Video[]> {
  try {
    return await invoke<LZIZY_Video[]>("get_channel_video_data", {channelIndex});
  } catch(e) {
    return Promise.reject(e);
  }
}

export async function search(name: string):Promise<LZIZY_Video_Base[]> {
  try {
    return await invoke<LZIZY_Video_Base[]>("search", {name});
  } catch(e) {
    return Promise.reject(e);
  }
}

export async function getTargetVideoDate(vid: number): Promise<LZIZY_Video> {
  try {
    return await invoke<LZIZY_Video>("get_target_video_data", {vid});
  } catch(e) {
    return Promise.reject(e);
  }
}